package com.example.protobuf2.controller;

import com.example.protobuf2.response.Judgement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.protobuf.format.JsonFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping(value = "/api")
public class QuestionnaireSaveController {

    @GetMapping("/json")
    public ResponseEntity<JudgeMapperObject> getJson() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JudgeMapperObject judgeMapperObject = objectMapper.readValue(new File("/home/huxin/data.txt"), JudgeMapperObject.class);
        return new ResponseEntity<>(judgeMapperObject, HttpStatus.OK);

    }

    @GetMapping("/protobuf")
    public ResponseEntity<byte[]> getProtobuf() throws IOException {
        Judgement.Judge.Builder builder = Judgement.Judge.newBuilder();
        new JsonFormat().merge(new FileInputStream(new File("/home/huxin/data.txt")), builder);
        return new ResponseEntity<>(builder.build().toByteArray(), HttpStatus.OK);
    }


    @GetMapping("/protobuf/stream")
    public ResponseEntity<Judgement.Judge> getProtobufStream(HttpServletResponse servletResponse) throws IOException {
        Judgement.Judge.Builder builder = Judgement.Judge.newBuilder();
        new JsonFormat().merge(new FileInputStream(new File("/home/huxin/data.txt")), builder);
        return new ResponseEntity<>(builder.build(), HttpStatus.OK);

    }

}
